<template>
  <div style="height: 100%;min-width:1000px;">
    <el-container class="wrapper">
      <el-header class="headerTop">
        <div class="header">
          <!-- <div class="logo">后台管理系统</div> -->
          <!-- 水平一级菜单 -->
          <div class="scroll_box">
            <div  @click="leftSlide" class="left-btn border-right">
                <i class="el-icon-d-arrow-left"></i>
            </div>
            <div class="scroll_menuwrapper" ref="menuwrapperCon">
            <el-menu 
              mode="horizontal"
              text-color="#fff"
              active-text-color="#639DE3"
              :default-active="activeIndex" 
              @select="handleSelect">
              <el-menu-item v-for="(item, index) in itemList" :index="index.toString()" :key="index">
                <span slot="title">{{ item.m_name }}</span>
              </el-menu-item>
            </el-menu>
            </div>
            <div  @click="rightSlide" class="right-btn border-left border-right">
              <i class="el-icon-d-arrow-right"></i>
            </div>
            <div class="header-right">
              <div class="header-right-box">
                <div @click="toDownloadCenter">
                  <img style="cursor: pointer;width: 25px;" src="@/assets/img/下载.png" alt="">
                </div>
                <span class="shu"></span>
                <!-- 切换主题 -->
                <!-- <div @click="handleChangeStyle()">
                  <el-tooltip content="切换主题" placement="bottom">
                    <i :class="globalTheme ? 'el-icon-moon' : 'el-icon-sunny'"></i>
                  </el-tooltip>
                </div> -->
                <!-- 语言切换 -->
                <el-popover placement="bottom" trigger="click" ref="popoverRefLang">
                  <ul style="margin: 0;height:100%;overflow:auto;cursor: pointer;">
                    <li
                    :style="{
                        backgroundColor:
                        lang == item.name
                            ? '#fff065'
                            : '#fff',
                      }"
                      v-for="item in langArr"
                      :key="item.id"
                      @click="handleChangelang(item)"
                    >
                      {{ item.name }}
                    </li>
                  </ul>
                  <span style="cursor: pointer;" slot="reference">
                    <img v-if="lang=='zh'" style="height:20px;" src="@/assets/img/zh.png" alt="">
                    <img v-else-if="lang=='ru'" style="height:20px;" src="@/assets/img/ru.png" alt="">
                    <img v-else-if="lang=='kz'" style="height:20px;" src="@/assets/img/kz.png" alt="">
                    <img v-else-if="lang=='en'" style="height:20px;" src="@/assets/img/en.png" alt="">
                  </span
                  >
                </el-popover>
                <!-- <span class="shu"></span>
                <el-popover popper-class="headerCity" placement="bottom" trigger="click" ref="popoverRefCity" @hide="CityHide">
                  <div>
                    <el-input
                      style="margin-bottom:4px;"
                      @input="filterCityInput"
                      v-model="filterCity"
                    ></el-input>
                  </div>
                  <ul style="margin: 0;height:100%;overflow:auto;">
                    <li
                      :style="{backgroundColor:current_city_id == item.id? '#fff065': '#fff',}"
                      class="city_btn_style"
                      v-for="item in CityList"
                      :key="item.id"
                      @click="selectCity(item)"
                    >
                      {{ item.name_current }}
                    </li>
                  </ul>
                  <span style="color: #fff; cursor: pointer" slot="reference"
                    >[{{ current_city_name }}]</span
                  >
                </el-popover> -->
                <span class="shu"></span>
                <el-dropdown trigger="click" placement="bottom" @command="handleCommand">
                  <el-tooltip class="item" effect="dark" :content="name" placement="bottom">
                    <el-avatar id="circle" size="small" :src="circleUrl"></el-avatar>
                  </el-tooltip>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="invitationCode">{{$t('AccountLang.Invitation_code')}}</el-dropdown-item>
                    <el-dropdown-item command="clearHeader">{{$t('common.clear_style')}}</el-dropdown-item>
                    <el-dropdown-item command="logOut">{{$t('WholeLang.safe_exit')}}</el-dropdown-item>
                    <!-- <el-dropdown-item command="editPassword">修改密码</el-dropdown-item> -->
                  </el-dropdown-menu>
                </el-dropdown>
                <!-- <span class="shu"></span>
                <span style="cursor: pointer;display: flex;align-items: center;gap: 5px;" @click="LogOut">
                  {{$t('WholeLang.safe_exit')}} 
                  <img style="height:16px;" src="@/assets/img/out.png" alt="">
                </span> -->
              </div>
            </div>
          </div>
        </div>
      </el-header>
      <el-container class="mid_container">
        <el-aside id="LeftMenu" style="margin-right: 20px; box-shadow: 7px 0px 8px #e6dfdf;" v-if="activeIndex.length>0" width="230px">
          <LeftMenu ref="LeftMenu"></LeftMenu>
        </el-aside>
        <el-container style="width:80%" id="ContentArea">
          <el-header style="height:52px;">
            <TabsCard ref="TabsCard"></TabsCard>
          </el-header>
          <el-main class="main_contant">
            <router-view></router-view>
          </el-main>
        </el-container>
      </el-container>
      <el-footer>
        <div class="box">{{$t('WholeLang.system_version')}}：{{EDITION}}</div>
        <div id="footerTitle" class="box">{{footerTitle}}</div>
        <div class="box">{{date|formateTime}}</div>
      </el-footer>
    </el-container>
    <DownLoadCenter  ref="downLoadCenter"></DownLoadCenter>
    <MessageLoading></MessageLoading>
    <ImgView></ImgView>
    <InvitationCode ref="invitationCode"></InvitationCode>
    <EditPassword ref="editPassword"></EditPassword>
    <!-- <CustomerService ref="CustomerService"></CustomerService> -->
  </div>
</template>

<script>
var	parseDate=function(datetime){
		return datetime<10?'0'+datetime:datetime;	
}
import DownLoadCenter from '@/components/common/DownloadCenter';
import LeftMenu from '@/components/common/LeftMenu';
import TabsCard from '@/components/common/TabsCard';
import MessageLoading from "@/components/common/MessageLoading"
import ImgView from "@/components/common/imgView"
import InvitationCode from "@/components/common/invitationCode"
import EditPassword from "@/components/common/editPassword"
import CustomerService from "@/components/common/CustomerService"
import { debounce } from '@/utils/func.js'
export default {
  components: {
    DownLoadCenter,
    LeftMenu,
    TabsCard,
    MessageLoading,
    ImgView,
    InvitationCode,
    EditPassword,
    CustomerService
  },
  data(){
    return{
      // 水平一级菜单栏的菜单
      itemList: [],
      activeIndex:'',
      globalTheme: false,
      lang:!!JSON.parse(localStorage.getItem('language'))?JSON.parse(localStorage.getItem('language')).lang:'zh',
      langArr:[
        {id:0,name:'简体中文',lang:'zh'},
        {id:1,name:'English',lang:'en'},
        {id:2,name:'Русский язык',lang:'ru'},
        // {id:3,name:'қазақ тілі',lang:'kz'},
      ],
      name: !!sessionStorage.getItem("userData")?JSON.parse(sessionStorage.getItem("userData")).name:'',
      //footer
      date:new Date(),
      EDITION: window.localStorage.getItem('EDITION'),
      circleUrl:'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      footerTitle:this.$t('WholeLang.footer_name'),

      CityList:[],
      current_city_id:'',
      current_city_name:'',
      filterCity:'',
    }
  },


  filters:{
			formateTime:function(val){
				var date=new Date(val);
        var wk = date.getDay()
				var year=date.getFullYear();
				var month=parseDate(date.getMonth()+1);
				var day=parseDate(date.getDate());
				var hours=parseDate(date.getHours());
				var min=parseDate(date.getMinutes());
				var sec=parseDate(date.getSeconds());
         let weeks=[]
        let lang=localStorage.getItem('language')?JSON.parse(localStorage.getItem('language')).lang:'zh'
        if(lang=='zh'){
           weeks = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
        }else if(lang=='ru'){
           weeks = ['воскресенье', 'понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота']
        }else if(lang=='kz'){
           weeks = ['жексенбі', 'дүйсенбі', 'сейсенбі', 'сәрсенбі', 'бейсенбі', 'жұма', 'сенбі']
        }else if(lang=='en'){
           weeks = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
        }
        let week = weeks[wk]
				return year+'-'+month+'-'+day+' '+hours+":"+min+":"+sec+' '+week;
			}
		},
  created() {
    if(!sessionStorage.getItem("userData")){
      this.$router.push({ path:"/Login" });
    }else{
      this.getItemList()
    }
    // this.$store.commit('RESET_STATE');
    var that=this;//作用域一致
    this.timer=setInterval(function(){
      that.date=new Date();
    },1000);
  },
  mounted() {
    // 刷新或关闭页面清除缓存退出登录
    window.onbeforeunload = function (e) {
      localStorage.removeItem("token");
    }
    if("WebSocket" in window){
        this.ws = new WebSocket(process.env.VUE_APP_WSS);
    }else{
        this.$notify.error({
          title: this.$t('ContactCustomersLang.error_title'),
          message: this.$t('ContactCustomersLang.error_text'),
        });
    }
    window.addEventListener('unload',this.handleWsClose)
    this.ws.addEventListener("open", this.handleWsOpen.bind(this), false);
    this.ws.addEventListener("close", this.handleWsClose.bind(this), false);
    this.ws.addEventListener("message", this.handleWsMessage.bind(this), false);
    let avatar_url=this.$baseUrl+JSON.parse(sessionStorage.getItem('userData')).avatar
    if(!!avatar_url){
      this.circleUrl=avatar_url
    }
    let tips=JSON.parse(sessionStorage.getItem('userData')).tips
    if(!!tips){
      this.footerTitle=tips
    }
    eventBus.$on('toDownloadCenter',()=>{
      this.toDownloadCenter()
    })
    // setTimeout(() => {
    //   this.getCityList()
    // }, 1000);
  },
  beforeDestroy(){
    this.ws.close()
			if(this.timer){
				clearInterval(this.timer);
			}
		},
  methods: {
    handleWsOpen() {
      console.log("总WebSocket连接成功");
      let obj={type:"init",id:JSON.parse(sessionStorage.getItem('userData')).uid};
      this.ws.send(JSON.stringify(obj));
    },
    handleWsClose(e) {
      // this.$get("index",{id:JSON.parse(sessionStorage.getItem('userData')).uid}).then((res) => {
      // });
      console.log("总WebSocket2关闭");
    },
    handleWsMessage(e) {
      let routerName=window.location.hash.split('/')[1]
      console.log("总消息",JSON.parse(e.data));
        const data = JSON.parse(e.data);
        let created_by=JSON.parse(sessionStorage.getItem('userData')).created_by.length==0?JSON.parse(sessionStorage.getItem('userData')).uid:JSON.parse(sessionStorage.getItem('userData')).created_by
        if(data.type=="chatMessage"){
          if(routerName!=='ContactCustomers'&&data.room_creator_id!==created_by){
            this.$notify({
              title: this.$t('common.customer_new_msg_title'),
              message: this.$t('common.new_msg_text'),
            });
          }
          if(routerName!=='CustomerService'&&data.room_creator_id===created_by){
            this.$notify({
              title: this.$t('common.service_new_msg_title'),
              message: this.$t('common.new_msg_text'),
            });
          }
        }
    },
    getItemList(){
      this.$get("menuHeader").then((res) => {
        if(res.success){
          this.itemList = res.data;
          if(!!localStorage.getItem('menuTopIndex')){
            this.handleSelect(localStorage.getItem('menuTopIndex'))
          }
        }
      });
      //老接口
      this.$get("getEcommercemenu").then((res) => {
        if(res.success){
          this.$store.commit('editmenuGroup', res.data);
          let arr=localStorage.getItem('tabsArr')
          if(!!arr){
              let arrCopy=JSON.parse(arr)
              arrCopy[0].m_name=this.$t('main.home')
              arrCopy.forEach(item => {
                let arr=res.data.filter(el=>{return el.route==item.route})
                if(arr.length>0){
                  item.m_name=arr[0].m_name
                }
              });
              localStorage.setItem('tabsArr',JSON.stringify(arrCopy))
              this.$store.commit('editTabsList',arrCopy)
          }
        }
      });
    },
    handleSelect(index){
      this.activeIndex=index
      localStorage.setItem('menuTopIndex',index)
      this.$nextTick(()=>{
        this.$refs.LeftMenu.getMenuList(this.itemList[index].m_id)
      })
    },
    //语言切换
    handleChangelang(item){
      if(this.lang!==item.lang){
        this.$refs.TabsCard.closeAll();
        this.lang=item.lang
        localStorage.setItem('language', JSON.stringify(item));// 会话存储选择的语言
        this.$i18n.locale = item.lang  
        this.$refs.popoverRefLang.doClose();
        window.setTimeout(()=>{
          location.reload(true)
        },100)
      }
    },
    //确认退出
    LogOut() {
      this.$confirm(this.$t('common.sure_out'), this.$t('common.prompt'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
        }).then(() => {
          this.$postForm("logout").then((res) => {
            if(res.success){
              this.$router.push({ path:"/Login" });
              this.$message.success(res.msg);
              this.resetState()
            }
          });
        }).catch(() => {});
      
    },
    resetState(){
      let EDITION=localStorage.getItem('EDITION')
      console.log(EDITION)
      localStorage.clear();
      let langObj=this.langArr.filter(el=>{return el.lang==this.lang})[0]
      localStorage.setItem('language',JSON.stringify(langObj))
      localStorage.setItem('EDITION',EDITION)
      localStorage.setItem('tabsCard',0)
      localStorage.setItem('tabsArr',JSON.stringify([{
        m_id: 0,
        m_name: this.$t('main.home'),
        route: 'Home',
        noClose: true
      }]))
      this.$store.commit('RESET_STATE')
    },
    // 左箭头
    leftSlide() {
        // 保存滚动盒子左侧已滚动的距离
        let left = this.$refs.menuwrapperCon.scrollLeft;
        let num = 0;
        clearInterval(this.timer);
        this.timer = null;
        this.timer = setInterval(() => {
            //   !left:已经滚动到最左侧
            if(!left){
              this.debounceFun()
              
            }
            //   一次性滚动距离（可调节）
            if (!left || num >= 300) {
                // 停止滚动
                clearInterval(this.timer);
                this.timer = null;
                return;
            }
            // 给滚动盒子元素赋值向左滚动距离
            this.$refs.menuwrapperCon.scrollLeft = left -= 30;
            // 保存向左滚动距离（方便判断一次性滚动多少距离）
            num += 30;
        }, 20);
        // 20：速度（可调节）
    },
    // 右箭头
    rightSlide() {
        // 保存滚动盒子左侧已滚动的距离
        let left = this.$refs.menuwrapperCon.scrollLeft;
        // 保存元素的整体宽度
        let scrollWidth = this.$refs.menuwrapperCon.scrollWidth;
        // 保存元素的可见宽度
        let clientWidth = this.$refs.menuwrapperCon.clientWidth;
        let num = 0;
        clearInterval(this.timer);
        this.timer = setInterval(() => {
            // 已经滚动距离+可见宽度
            // left+clientWidth>=scrollWidth：滚动到最右侧
            if(left + clientWidth >= scrollWidth){
              this.debounceFun()
            }
            // num>=300一次性滚动距离
            if (left + clientWidth >= scrollWidth || num >= 300) {
                clearInterval(this.timer);
                return;
            }
            // 给滚动盒子元素赋值向左滚动距离
            this.$refs.menuwrapperCon.scrollLeft = left += 30;
            // 保存向左滚动距离（方便判断一次性滚动多少距离）
            num += 30;
        }, 20);
        // 20：速度（可调节）
    },
    //函数防抖（当不触发后n秒后执行）
    debounceFun:debounce(function(){
      this.$message.warning(this.$t('main.SlideNoMore'),1000);
    }, 500),
    //老接口
    handleCommand(command) {
      if(command=='invitationCode'){
        this.$refs.invitationCode.init();
      }else if(command=='clearHeader'){
        this.$get("del_th").then((res) => {
          if(res.success){
            this.$message.success(res.msg);
          }
        });
      }else if(command=='editPassword'){
        this.$refs.editPassword.init();
      }else if(command=='logOut'){
        this.LogOut();
      }
    },
    toDownloadCenter(){
      this.$refs.downLoadCenter.init()
    },
    async getCityList() {
      await this.$get("visibleAddress",{type:1}).then((res) => {
        this.OldCityList = res.data.start_local;
        this.CityList=JSON.parse(JSON.stringify(this.OldCityList)) 
      });
      this.$get("getMemberLocal").then((res) => {
        if(this.OldCityList.length>0){
          this.current_city_id = res.data.lid;
          if(this.OldCityList.filter(el=>{return el.id==this.current_city_id}).length>0){
            this.current_city_name= this.OldCityList.filter(el=>{return el.id==this.current_city_id})[0].name_current
          }else{
            this.current_city_id =this.OldCityList[0].id
            this.current_city_name=this.OldCityList[0].name_current
            this.selectCity({id:this.current_city_id})
          }
        }else{
          this.current_city_id =''
          this.current_city_name=''
        }
      });
    },
    //选择城市
    selectCity(data) {
      let params = new FormData();
      params.append("lid", data.id);
      this.$postForm("saveMemberLocal", params).then((res) => {
        this.current_city_id = data.id;
        this.current_city_name= this.OldCityList.filter(el=>{return el.id==this.current_city_id})[0].name_current
        eventBus.$emit("changeCity");
        this.$refs.popoverRefCity.doClose();
      });
    },
    filterCityInput(){
      this.CityList=[]
      this.OldCityList.forEach(item => {
        if(item.name_current.includes(this.filterCity)){
          this.CityList.push(item)
        }
      });
    },
    CityHide(){
      this.filterCity=''
      this.CityList=JSON.parse(JSON.stringify(this.OldCityList))
    },
  }
}
</script>

<style lang="less">
.wrapper {
  width: 100%;
  height: 100%;
  background: #f0f0f0;
}
.headerTop{
  min-width: 1000px;
  height: 50px !important;
  background-color: #6c9ee5 !important;
}
.el-header{
  color: #333;
  text-align: center;
  padding-left: 0;
  .header {
    background-color: unset;
    position: relative;
    box-sizing: border-box;
    width: 100%;
    line-height: 1;
    .el-menu.el-menu--horizontal {
      border-bottom: none !important;
      // float: left;
      display: flex;
      gap: 10px;
      background: transparent;
      .el-menu-item.is-active {
        font-weight: bold;
        background-color: #eaf0fc;
      }
      .el-menu-item {
        float: unset;
        font-size: 18px;
        height: 50px;
        line-height: 50px;
        border: 0 !important;
        font-weight: 700;
      }
      .el-menu-item:hover {
        background-color: #eaf0fc;
        color: #639DE3 !important;
      }
    }
    .header-right {
      float: right;
      height: 50px;
      padding-right: 10px;
      .header-right-box {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        height: 100%;
        gap: 10px;
        color: #fff;
        .shu{
          height: 20px;
          margin: 0 5px;
          border: 1px solid #fff;
        }
      }
    }
  }
}
.mid_container{
  background-color: #fff;
  height: 1vh;
  // .el-aside{
  //   background-color: #001529;
  // }
  .el-header{
    // height: auto !important;
    line-height: 1;
    margin: 0;
    padding: 0;
  }
  .el-main{
    padding: 0;
    position: relative;
    .content-box{
      left: 0;
      top: 0;
      padding: 15px;
      padding-left: 0;
      background-color: #fff;
    }
    .operateBtnItem{

      float: left;
      position: relative;
      display: flex;
      align-items: center;
      margin: 0 10px;
      padding: 3px 5px;
      color: #606266;
      border-radius: 4px;
      border: 1px solid transparent;
      cursor: pointer;
      img{
        width: 14px;
        height: 14px;
      }
      .text{
        min-width: auto;
        margin-left: 5px;
      }
      .shu{
        position: absolute;
        left: -10px;
        min-width: 1px;
        background-color: #666;
        
      }
    }
    .operateBtnItem:hover{
      color: #409eff;
      background-color: #c6e2ff;
      border: 1px solid #ecf5ff;
    }
  }
}
.el-footer {
  height: 30px !important;
  background: #f3f3f3;
  border: 1px solid #99bce8;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .box{
    // position: absolute;
    // top:4px;
    font-size: 9pt;
    font-family: Tahoma, Verdana, 宋体;
    color:#000000
  }
}

/* --------------- 水平一级菜单栏的样式--------------------- */
.scroll_box{
    width: 100%;
    float: left;
    display: flex;
    gap: 10px;
    justify-content: space-between;
  .scroll_menuwrapper {
      flex: 1;
      overflow-x: scroll;
      margin: 0 5px;
      display: flex;
      float: left;
  }
  .left-btn,
  .right-btn {
      width: 50px;
      height: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 18px;
      color: #fff;
      cursor: pointer;
  }
  .border-left {
      border-left: 1px solid #ccc;
  }
  .border-right {
      border-right: 1px solid #ccc;
  }
  /*隐藏滚动条*/
  .scroll_menuwrapper::-webkit-scrollbar {
      display: none;
  }
}
.city_btn_style {
  padding: 3px 2px;
  cursor: pointer;
}
.city_btn_style:hover {
  background-color: #fff065 !important;
}
</style>